/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Post;

import DAO.Usuario.HibernateUtil;
import Model.PostInterface;
import Model.Post;
import Model.Localizacao;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.hibernate.Session;

/**
 *
 * @author pedro
 */
@Path("/filtroPost")
public class Filtro {

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    public Response filtroPost(String selectedFilter) {
        
        String json;
        String parametro = "";
        Gson gson = new Gson();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy ");
        
        Type collectionType = new TypeToken<List<String>>() {
        }.getType();
        List<String> params = gson.fromJson(selectedFilter, collectionType);

        ArrayList<PostInterface> postInterface = new ArrayList<PostInterface>();

        for (int i = 0; i < params.size(); i++) {

            parametro = parametro + " post.localizacao= lock AND post.codCategoria=" + params.get(i) + " OR";
        }

        parametro = parametro.substring(0, parametro.length() - 2);


        Session session = HibernateUtil.getSession();
        HibernateUtil.beginTransaction();
        ArrayList<Localizacao> lista = (ArrayList<Localizacao>) session.createQuery("Select  lock  from Localizacao as lock, Post as post WHERE  "+parametro+"").list();


        session.getTransaction().commit();
        HibernateUtil.commitTransaction();

        ArrayList<Post> arr;

        for (int i = 0; i < lista.size(); i++) {
            PostInterface ps = new PostInterface();
            arr = new ArrayList<Post>(lista.get(i).getPosts());

            ps.setCod(arr.get(0).getCod());
            ps.setData(sdf.format(arr.get(0).getData()));
            ps.setCodCategoria(arr.get(0).getCodCategoria());
            ps.setDescricao(arr.get(0).getDescricao());
            ps.setImagem(arr.get(0).getImagem());
            ps.setLatitude(lista.get(i).getLatitude());
            ps.setLocal(lista.get(i).getLocal());
            ps.setLongitude(lista.get(i).getLongitude());
            ps.setUsuario(arr.get(0).getCodUsuario());
            ps.setTitulo(arr.get(0).getTitulo());
            postInterface.add(ps);
        }



        Gson g = new Gson();
        json = g.toJson(postInterface);


        HibernateUtil.closeSession();
       
        return Response.status(201).entity(json).build();

    }
}
